//
//  ViewController.m
//  KingReaderSDKDemo
//
//  Created by wangbc on 16/3/24.
//  Copyright © 2016年 Shanghai Lianyou Network Technology Co., Ltd. All rights reserved.
//

#import "ViewController.h"
#import "KRSDKDemoViewController.h"
#import "KRTestViewController.h"
#import "KingReaderSDK.h"
#import "ThirdLoginSDK.h"

//此处为使用idfa的SDK用户调用，如不使用请勿import
#import <AdSupport/ASIdentifierManager.h>

#define Random arc4random() % 256 / 255.0f
#define ColorRandom [UIColor colorWithRed:Random green:Random blue:Random alpha:1.0f]
#define kBaseHeight [[UIScreen mainScreen]bounds].size.height

/**
 *  Demo使用:
 请查看KingReaderSDK.h说明使用和readme
 */
@interface ViewController ()

@property (nonatomic, assign) BOOL addItem;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNotification];
    //错误示例❌
   // [self invaildUnid];
}

#pragma mark - ==========  添加SDK内部通知监听  ==========
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:KingReaderSDKTabbarClick object:nil];
}

- (void)handleNotification:(NSNotification *)notice {
    NSNumber *index = notice.object;
    NSLog(@"index=%@",index);
}

#pragma mark - ==========  UI配置处理  ==========
//自定义颜色: 随机色
- (IBAction)tabBarColor:(UIButton *)sender {
    [KingReaderSDK setNavigationForgroundColor:ColorRandom];
    [KingReaderSDK setTabbarSelectedColor:ColorRandom];
    [KingReaderSDK setTabbarNormalColor:ColorRandom];
}

#pragma mark - ==========  隐藏部分按钮和信息  ==========
//点击隐藏返回按钮
- (IBAction)hiddenBackButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    [KingReaderSDK setHiddenMainInterfaceBackButton:sender.selected];
}

//点击隐藏收费信息
- (IBAction)hiddenPayInfo:(UIButton *)sender {
    sender.selected = !sender.selected;
    [KingReaderSDK setHiddenPayEntrance:sender.selected];
}

#pragma mark - ==========  添加items  ==========
//点击添加tabBarItem
- (IBAction)addItem:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.addItem = sender.selected;
}

#pragma mark - ==========  添加书架原生广告  ==========
//如果不展示广告请不要调用
- (IBAction)addNativeAd:(UIButton *)sender {
    NSString *appKey = @"广点通应用AppKey";
    NSString *placementId = @"广点通广告位id";
    [KingReaderSDK usingGDTNativeAdWithAppKey:appKey placementId:placementId];
}

#pragma mark - ==========  分享功能  ==========
- (IBAction)shareFunction:(UIButton *)sender {
    [KingReaderSDK usingShareFunctionWithWXInstall:YES qqInstall:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleShareContent:) name:KingReaderSDKShareContent object:nil];
}

- (void)handleShareContent:(NSNotification *)notice {
    if ([notice.name isEqualToString:KingReaderSDKShareContent]) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:notice.userInfo];
        KRSDKShareType type = [[dict valueForKey:KingReaderSDKShareType] integerValue];
        [ThirdLoginSDK share:(SSDKShareType)type parameters:dict onStateChanged:^(SSDKResponseState state, NSDictionary *userData, NSError *error) {
            NSDictionary *userInfo = @{KingReaderSDKShareState_Current : @(state)};
            dispatch_async(dispatch_get_main_queue(), ^{//保证通知的发送与接收在同一线程内。
                [[NSNotificationCenter defaultCenter] postNotificationName:KingReaderSDKShareState object:nil userInfo:userInfo];
            });
        }];
    }
}

#pragma mark - ==========  添加内购以便用于审核  ==========
- (IBAction)useInAppPerchase:(UIButton *)sender {
    [KingReaderSDK setHiddenPayEntrance:YES];//审核完成后，设置为NO。
    NSString *appUniqueId = @"XXXXX";
    NSArray *originIdentifiers = @[@"com.kingreader.6yuan", @"com.kingreader.18yuan", @"com.kingreader.30yuan", @"com.kingreader.108yuan", @"com.kingreader.30vip.sale", @"com.kingreader.30tvip", @"com.kingreader.90tvip", @"com.kingreader.180tvip", @"com.kingreader.360tvip"];
    NSMutableArray *identifiers = [NSMutableArray array];
    for (NSString *str in originIdentifiers) {
        [identifiers addObject:[appUniqueId stringByAppendingString:str]];
    }
    [KingReaderSDK bringInAppStoreIdentifiers:identifiers];
}

#pragma mark - ==========  登录注册获取开卷根视图  ==========
- (IBAction)buttonTapped:(id)sender {
    
#pragma mark - 创建item视图
    KRSDKDemoViewController *sdkDemoViewController = [[KRSDKDemoViewController alloc] initWithNibName:@"KRSDKDemoViewController" bundle:nil];
    sdkDemoViewController.titleName = @"砖石";
    
    KRTestViewController *sdkTestViewController = [[KRTestViewController alloc] initWithNibName:@"KRTestViewController" bundle:nil];
    sdkTestViewController.titleName = @"测试";
    
#pragma mark - 获取书城免费频道页面
    UIViewController *freeChannel = [KingReaderSDK freeBooksChannelWithViewControllerHeight:kBaseHeight - 64 - 49];
    
    if (![KingReaderSDK isLogined]) {
        NSString *unid = @"SDK用户传入的Unid(请查看 pragma mark - 错误示例)";
        unid = [self getVaildUnid];
#warning unid的传入请务必保证唯一性，请看错误的示例和建议方案！！！
        [KingReaderSDK loginWithUniqueId:unid channelId:99 completeBlock:^(NSString *error, BOOL succeed) {
            if (succeed) {
                if (self.addItem) {
                 #pragma mark - 添加item视图（1️⃣2️⃣两个二选一）
                    //1️⃣添加两个页面
                    [KingReaderSDK addTabButtons:@[@"钻石",@"测试"] imageNames:@[@"jiyin", @"diamond"] viewControllers:@[sdkDemoViewController,sdkTestViewController]];
                    
                    //2️⃣设置开卷免费频道页面 为 第4个tab
                    [KingReaderSDK addTabButton:@"砖石" imageName:@"diamond" viewController:freeChannel atIndex:3];
                }
                UIViewController *vc = [KingReaderSDK rootViewController];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    } else {
        if (self.addItem) {
            #pragma mark - 添加item视图（1️⃣2️⃣两个二选一）
            UIImage *normalImage = [UIImage imageNamed:@"diamond"];
            UIImage *selectedIamge = [UIImage imageNamed:@"diamond2"];
            UIImage *normalImage1 = [UIImage imageNamed:@"diamond"];
            UIImage *selectedIamge1 = [UIImage imageNamed:@"diamond2"];
            
            //1️⃣添加两个页面
            [KingReaderSDK addTabButtons:@[@"钻石",@"测试"]  normalImages:@[normalImage, normalImage1] selectedImages:@[selectedIamge, selectedIamge1] viewControllers:@[sdkDemoViewController,sdkTestViewController]];
            
            //2️⃣添加一个页面
            [KingReaderSDK addTabButton:@"砖石" normalImage:normalImage selectedImage:selectedIamge viewController:sdkDemoViewController atIndex:999];
        }
        UIViewController *vc = [KingReaderSDK rootViewController];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - ==========  错误示例  ==========
- (NSString *)getInvailedUniqueIdentifier {
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adid;
}

//错误原因示例
- (void)invaildUnid {
    //打开手机设置->隐私->广告->打开限制广告跟踪, 然后运行上面的代码
    NSString *unid = [self getInvailedUniqueIdentifier];
    if ([unid isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
        NSException *exception = [NSException exceptionWithName:@"Unid不具唯一性" reason:@"该ID为固定ID，服务器无法区分用户唯一性" userInfo:nil];
        //如果用户进行上述设置则会发生下面的问题。所以务必保证此处的唯一性。否则服务器将会混淆用户，导致用户纠纷。
        @throw exception;
    }
}

//可选方案如下：
//使用bundleID+channelID+idfv+注册时间来保证唯一性
//此处存储unid可以考虑keychain存储。
- (NSString *)getVaildUnid {
    NSString *bundleID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return [[bundleID stringByAppendingString:idfv] stringByAppendingString:[self fetchTimeNow:99]];
}

- (NSString *)fetchTimeNow:(int)channelID {
    //demo的channelID=99，用户可以自己传入自己的channelID
    NSString *date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd-hh:mm:ss:SSS"];
    date = [formatter stringFromDate:[NSDate date]];
    NSString *timeNow = [[NSString alloc] initWithFormat:@"-%d-%@", channelID, date];
    return timeNow;
}
@end
